﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace DotNETX.Utility.Text
{
    public static class RegexpUtils
    {
        public static Dictionary<string,Dictionary<RegexOptions, Regex>> RegexCache = new Dictionary<string,Dictionary<RegexOptions,Regex>>();
        public static Regex CreateRegex(string pattern, RegexOptions opt)
        {
         
            Regex regex = null;
            if(RegexCache.ContainsKey(pattern) && RegexCache[pattern]!= null && RegexCache[pattern].ContainsKey(opt))
            {
                regex = RegexCache[pattern][opt];
            }
            else
            {
                regex = new Regex(pattern, opt);
                if(!RegexCache.ContainsKey(pattern))RegexCache.Add(pattern, new Dictionary<RegexOptions,Regex>());
                RegexCache[pattern].Add(opt, regex);
            }
            return regex;
        }

        public static bool IsMatch( string input, string pattern, RegexOptions opt = RegexOptions.None)
        { 
            Regex regex = CreateRegex(pattern, opt);
            return regex.IsMatch(input);
        }

        public static Match Match(string input, string pattern, RegexOptions opt = RegexOptions.None)
        {
            Regex regex = CreateRegex(pattern, opt);
            Match m = regex.Match(input);
            return m;
        }

        public static MatchCollection Matchs(string input, string pattern, RegexOptions opt = RegexOptions.None)
        {
            Regex regex = CreateRegex(pattern, opt);
            MatchCollection mc = regex.Matches(input);
            return mc;
        }
        
        public static string Replace(string input, string pattern, string replacement, RegexOptions opt = RegexOptions.None)
        {
            Regex regex = CreateRegex(pattern, opt);
            string str = regex.Replace(input, replacement);
            return str;
        }

        public static string Replace(string input, string pattern, MatchEvaluator matchEvaluator, RegexOptions opt = RegexOptions.None)
        {
            Regex regex = CreateRegex(pattern, opt);
            string str = regex.Replace(input, matchEvaluator);
            return str;
        }
    }
}
